<template>
  <vab-dialog
    v-model="dialogFormVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    show-fullscreen
    :title="title"
    width="50%"
  >
    <div class="upload">
      <div class="download" style="margin-bottom: 10px">
        <el-table :data="uploadData">
          <el-table-column label="模板" prop="name" />
          <el-table-column align="center" label="操作" width="100">
            <el-button :icon="Download" size="small" type="primary" @click="templatedownload"> 下载 </el-button>
          </el-table-column>
        </el-table>
      </div>
      <el-upload
        accept=".xlsx"
        :auto-upload="false"
        :file-list="fileList"
        :limit="limit"
        :multiple="false"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :on-remove="handleRemove"
      >
        <el-button :icon="Finished" size="small" type="primary"> 选择文件 </el-button>
      </el-upload>
    </div>
    <template #footer>
      <div style="position: relative; padding-right: 15px; text-align: right">
        <el-button :loading="loading" type="success" @click="changFile"> 确认导入 </el-button>
        <el-button type="info" @click="handleClose">关闭</el-button>
      </div>
    </template>
  </vab-dialog>
</template>

<script>
import { Download, Finished } from "@element-plus/icons-vue";
import VabDialog from "@/plugins/VabDialog/index.vue";
import { importFile, downloadtemplate, downloadFile } from "@/api/mains";
import { ElLoading } from "element-plus";
import { succMsg } from "@/utils/MessageUtils";

export default defineComponent({
  name: "VabUpload",
  components: {
    VabDialog
  },
  props: {
    url: {
      type: String,
      default: "",
      required: true
    },
    name: {
      type: String,
      default: "",
      required: true
    }
  },
  emits: {
    fetchdata: null //fetchData事件没有检验
  },
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance();
    const state = reactive({
      loading: false,
      title: "上传",
      tempurl: "templateFile",
      tempFrom: {
        fileName: props.name
      },
      dialogFormVisible: false,
      fileList: [],
      uploadData: [{ name: props.name }],
      limit: 1
    });

    const handleChange = fileList => {
      state.fileList.push(fileList);
    };

    const changFile = async () => {
      state.loading = true;
      if (state.fileList.length === 0) {
        proxy.$baseMessage("请选取文件", "warning");
        state.loading = false;
        return;
      } else {
        const loading = ElLoading.service({
          lock: true,
          text: "导入中，请稍候...",
          background: "rgba(0, 0, 0, 0.7)"
        });
        const formdata = new FormData();
        state.fileList.forEach(file => {
          formdata.append("upfile", file.raw);
        });
        const { msg } = await importFile(props.url, formdata);
        succMsg(msg);
        state.fileList = [];
        emit("fetchdata");
        handleClose();
        state.loading = false;
        loading.close();
      }
    };

    const handleExceed = files => {
      proxy.$baseMessage(
        `当前限制选择 ${state.limit} 个文件，本次选择了
                ${files.length}
                个文件`,
        "error",
        "vab-hey-message-error"
      );
    };

    const handleRemove = (file, fileList) => {
      console.log(file);
      state.fileList = fileList;
    };

    const handleShow = () => {
      state.title = "导入";
      state.dialogFormVisible = true;
    };
    const handleClose = () => {
      state.dialogFormVisible = false;
    };

    const templatedownload = async () => {
      proxy.$baseConfirm("你确定要下载此文件吗", null, async () => {
        await downloadtemplate(state.tempurl, state.tempFrom)
          .then(res => {
            if (res.code == 200) {
              const filepath = res.data.filepath;
              if (filepath != null && filepath != "") {
                // console.log(filepath)
                proxy.$baseMessage(res.msg, "success", false, "vab-hey-message-success");
                downloadFile(props.url, { filename: filepath })
                  .then(res => {
                    const link = document.createElement("a");

                    const blob = new Blob([res], {
                      type: "application/octer-stream"
                    });

                    link.style.display = "none";

                    link.href = URL.createObjectURL(blob);

                    link.setAttribute("download", props.name);

                    document.body.appendChild(link);

                    link.click();

                    document.body.removeChild(link);
                  })
                  .catch(err => {
                    console.log(err);
                  });
              }
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    };

    return {
      ...toRefs(state),
      changFile,
      handleShow,
      handleClose,
      handleChange,
      templatedownload,
      handleExceed,
      handleRemove,
      Download,
      Finished
    };
  }
});
</script>

<style lang="scss" scoped>
.upload {
  height: 45vh;
  .upload-content {
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }
    :deep() {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px;
        border: 2px dashed #c0ccda;
      }
      .el-upload-list--picture {
        margin-bottom: 20px;
      }
      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px;
        }
      }
    }
  }
}
.text-left {
  padding-left: 30px;
  text-align: left;
}
h3 {
  padding-bottom: 20px;
}
.cust_btn30 {
  padding-top: 30px;
  padding-bottom: 60px;
}
.text_fise {
  font-size: 16px;
}
.text_fise > div {
  padding-bottom: 20px;
}
</style>
